#include<errno.h>
#include<fcntl.h>
#include<iostream>
#include"inputmemorystream.h"
#include<sys/mman.h>
#include<cstdio>
#include<cstring>

void inputmemorystream::open_s(const char *fileName)
{
	this->fd = open(fileName, O_RDONLY);
	if(this->fd == -1)
                std::cout << "Error opening stream: " << strerror( errno ) << std::endl;
}

int inputmemorystream::read_next()
{
	if(this->rcount == 0 )
	{
		if((this->raddress = (int*)mmap(0, BUFFER*sizeof(int), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
			std::cout << "Error reading from stream: " << strerror( errno ) << std::endl;
		this->roffset = BUFFER*sizeof(int);
	}
	else if(this->rcount % BUFFER ==0 && this->rcount!=0)
	{
		munmap(this->raddress, this->rcount*sizeof(int));
		if((this->raddress = (int*)mmap(0, BUFFER*sizeof(int), PROT_READ, MAP_SHARED, fd, this->roffset)) == MAP_FAILED)
	        	std::cout << "Error reading from stream: " << strerror( errno ) << std::endl;
		this->roffset += BUFFER*sizeof(int);
		this->rcount = 0;
	}

	if(!end_of_stream())
		return this->raddress[this->rcount++];
	else
	{
		munmap(this->raddress, this->rcount*sizeof(int));
		return EOF;
	}
}

bool inputmemorystream::end_of_stream()
{
	if(this->raddress[this->rcount] == EOF)
		return true;
	return false;
}

void inputmemorystream::close_i()
{
	 close(this->fd);
}
